package com.igeek.ch02.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2022/12/8 16:57
 *
 * ThreadLocal + C3P0
 */
public class JDBCUtils {

    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

    //线程变量  Key->ThreadLocal  Value->Connection
    //多线程并发操作时，可以确保每个线程操作的是自己的线程变量中的值Connection连接对象，从而确保事务
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    //获取数据源的方法
    public static DataSource getDataSource(){
        return dataSource;
    }

    //获取连接的方法
    public static Connection getConn(){
        Connection connection = tl.get();
        try {
            if(connection==null || connection.isClosed()){
                connection = dataSource.getConnection();
                tl.set(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //归还连接的方法
    public static void close(){
        Connection connection = tl.get();
        try {
            if(connection!=null && !connection.isClosed()){
                //C3P0的close()，归还连接至连接池中，不会进行物理释放
                connection.close();
                //为了确保不会发生内存泄漏
                tl.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
